//
//  CheckBoxView.m
//  PhongThuyHuongNha
//
//  Created by Le Anh Tai on 9/28/13.
//  Copyright (c) 2013 Le Anh Tai. All rights reserved.
//

#import "CheckBoxView.h"
#import <QuartzCore/QuartzCore.h>
#import "UIConstants.h"
#import "Utility.h"

#define CHECKBOX_SIZE 30
#define PADDING 5

@implementation CheckBoxView

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self)
    {
        [self initialize];
    }
    
    return self;
}

- (id)initWithCoder:(NSCoder *)aDecoder
{
    self = [super initWithCoder:aDecoder];
    if (self)
    {
        [self initialize];
    }
    
    return self;
}

- (void)initialize
{
    //checked
    _checkedImageView = [[UIImageView alloc] init];
    _checkedImageView.layer.cornerRadius = 4;
    _checkedImageView.layer.borderColor = [UIColor grayColor].CGColor;
    _checkedImageView.layer.borderWidth = 1;
    [self addSubview:_checkedImageView];
    
    //title
    _titleLabel = [[UILabel alloc] init];
    _titleLabel.backgroundColor = [UIColor clearColor];
    [self addSubview:_titleLabel];
    
    
    //tap gesture
    UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleTapGesture:)];
    [self addGestureRecognizer:tapGesture];
    
    self.backgroundColor = [UIColor clearColor];
    _alignment = NSTextAlignmentLeft;
}

- (void)handleTapGesture:(UITapGestureRecognizer*)tapGesture
{
    self.checked = !_checked;
    
    if ([_delegate respondsToSelector:@selector(checkBox:valueChanged:)])
    {
        [_delegate checkBox:self valueChanged:_checked];
    }
}

-(void)layoutSubviews
{
    if (_alignment == NSTextAlignmentRight)
    {
        _checkedImageView.frame = RECT(self.width - CHECKBOX_SIZE, (self.height - CHECKBOX_SIZE)/2, CHECKBOX_SIZE, CHECKBOX_SIZE);
        _titleLabel.frame = RECT(0, 0, self.width - _checkedImageView.width, self.height);
    }
    else
    {
        CGSize labelSize = [Utility getSizeOfString:_titleLabel.text font:_titleLabel.font width:self.width - CHECKBOX_SIZE];
        _titleLabel.frame = RECT(0, 0, labelSize.width, self.height);
        _checkedImageView.frame = RECT(_titleLabel.right, (self.height - CHECKBOX_SIZE)/2, CHECKBOX_SIZE, CHECKBOX_SIZE);
    }
}

- (void)setFrame:(CGRect)frame
{
    [super setFrame:frame];
    
    [self layoutSubviews];
}

- (void)setAlignment:(NSTextAlignment)alignment
{
    _alignment = alignment;
    _titleLabel.textAlignment = _alignment == NSTextAlignmentCenter? NSTextAlignmentLeft:_alignment;
    
    [self setFrame:self.frame];
}

- (void)setChecked:(BOOL)checked
{
    _checked = checked;
    
    if (_checked)
    {
        [_checkedImageView setImage:[UIImage imageNamed:@"checked.png"]];
    }
    else
    {
        [_checkedImageView setImage:nil];
    }
}


@end
